#include "Door.h"
#include "Object.h"
#include "../Graphic/GraphicManager.h"
#include "../Game/Level.h"
#include <math.h>
#include <GL/glut.h>
#include <iostream>
#include <math.h>


//Render method
void cDoor::Render()
{
  
   //Get game graphic properties
  int miTileWidth = cGraphicManager::Get().GetTileWidth();
  int miTileHeight = cGraphicManager::Get().GetTileHeight();
  unsigned int luiXScreenOffset = cGraphicManager::Get().GetXScreenOffset();
  unsigned int luiYScreenOffset = cGraphicManager::Get().GetYScreenOffset();
  unsigned int luiGameHeight = cGraphicManager::Get().GetGameHeight();
 
  
  double coordx_tile = 0.0f;
  double coordy_tile = 0.0f;
  
  switch (muiCurrentFrame)
  {
  case 1:
    coordx_tile = 0.5f;
    break;
  case 2:
    coordy_tile = 0.5f;
    break;
  case 3:
    coordx_tile = coordy_tile = 0.5f;
  }
  double cte = 0.375f;

  int tex1=mTexture.GetID();
  glEnable(GL_TEXTURE_2D);
  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  glBindTexture(GL_TEXTURE_2D, tex1);  
 
  //Draw the Object
  glColor3f(1.0,1.0,1.0);
 
  glBegin(GL_QUADS);
    
  glTexCoord2f(coordx_tile, coordy_tile + cte);	
  glVertex2i(muiX*miTileWidth, muiY*miTileHeight);
	glTexCoord2f(coordx_tile+cte,coordy_tile+cte);	
  glVertex2i((muiX+1)*miTileWidth , muiY*miTileHeight);
	glTexCoord2f(coordx_tile+cte,coordy_tile       );	
  glVertex2i((muiX+1)*miTileWidth, (muiY+1)*miTileHeight);
	glTexCoord2f(coordx_tile       ,coordy_tile       );	
  glVertex2i(muiX*miTileWidth , (muiY+1)*miTileHeight);
  glEnd();  
}

 
//Update time elapsed
void cDoor::Update(float lfTimeStep)
 {
  //Get the player
  cObject * loPlayer = cLevel::Get().GetPlayer();
  //Get the relative position of the player
  eOrientation leOrientation = loPlayer->GetOrientation(muiX, muiY);

  //Change door status
  if ((leOrientation == eO_Over) && (mbDoorOpened == false) && (((cPlayer *)loPlayer)->HasObject(msKey)))
    mbDoorOpened = true;

  //Set the propper texture
  if (mbDoorOpened)  
    mTexture = cTextureManager::Get().GetTexture("Data/DoorOpen.png");
  else
    mTexture = cTextureManager::Get().GetTexture("Data/Door.png");

  mfElapsedTime += fabs(lfTimeStep);
  if (mfElapsedTime < 0.250) return;
  if ((muiCurrentFrame == 3) || (muiCurrentFrame == 0)) miSigInc = -miSigInc;
  muiCurrentFrame = (muiCurrentFrame + (1 * miSigInc));
  
  mfElapsedTime = 0.0f;
 }